package com.douyinkan.util;

import org.springframework.stereotype.Component;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.mp4.Mp4Directory;
import com.drew.metadata.mp4.media.Mp4VideoDirectory;
import com.drew.metadata.jpeg.JpegDirectory;
import com.drew.metadata.png.PngDirectory;

import java.io.File;
import java.io.IOException;

@Component
public class MediaUtil {

    public static class MediaInfo {
        private Double duration; // in seconds
        private Integer width;
        private Integer height;
        private String codec;

        public MediaInfo(Double duration, Integer width, Integer height, String codec) {
            this.duration = duration;
            this.width = width;
            this.height = height;
            this.codec = codec;
        }

        // Getters
        public Double getDuration() { return duration; }
        public Integer getWidth() { return width; }
        public Integer getHeight() { return height; }
        public String getCodec() { return codec; }
    }

    public MediaInfo extractVideoInfo(String filePath) {
        try {
            File file = new File(filePath);
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            Integer width = null, height = null;
            Double duration = null;
            String codec = "unknown";

            // 尝试从MP4目录获取视频信息
            Mp4VideoDirectory videoDirectory = metadata.getFirstDirectoryOfType(Mp4VideoDirectory.class);
            if (videoDirectory != null) {
                width = videoDirectory.getInteger(Mp4VideoDirectory.TAG_WIDTH);
                height = videoDirectory.getInteger(Mp4VideoDirectory.TAG_HEIGHT);
            }

            Mp4Directory mp4Directory = metadata.getFirstDirectoryOfType(Mp4Directory.class);
            if (mp4Directory != null) {
                duration = mp4Directory.getDoubleObject(Mp4Directory.TAG_DURATION_SECONDS);
                String fourCC = mp4Directory.getString(Mp4Directory.TAG_MAJOR_BRAND);
                if (fourCC != null) {
                    codec = fourCC;
                }
            }

            return new MediaInfo(duration, width, height, codec);
        } catch (ImageProcessingException | IOException e) {
            System.err.println("Error extracting video info with metadata-extractor: " + e.getMessage());
            // 返回默认值
            return new MediaInfo(null, null, null, "unknown");
        }
    }

    public MediaInfo extractImageInfo(String filePath) {
        try {
            File file = new File(filePath);
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            Integer width = null, height = null;
            String codec = "unknown";

            // 从不同的目录类型获取图像信息
            ExifSubIFDDirectory exifDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if (exifDirectory != null) {
                width = exifDirectory.getInteger(ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH);
                height = exifDirectory.getInteger(ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT);
            }

            // 如果EXIF中没有找到，尝试其他图像目录
            if (width == null || height == null) {
                JpegDirectory jpegDirectory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
                if (jpegDirectory != null) {
                    width = jpegDirectory.getInteger(JpegDirectory.TAG_IMAGE_WIDTH);
                    height = jpegDirectory.getInteger(JpegDirectory.TAG_IMAGE_HEIGHT);
                }
            }

            if (width == null || height == null) {
                PngDirectory pngDirectory = metadata.getFirstDirectoryOfType(PngDirectory.class);
                if (pngDirectory != null) {
                    width = pngDirectory.getInteger(PngDirectory.TAG_IMAGE_WIDTH);
                    height = pngDirectory.getInteger(PngDirectory.TAG_IMAGE_HEIGHT);
                }
            }

            return new MediaInfo(null, width, height, codec);
        } catch (ImageProcessingException | IOException e) {
            System.err.println("Error extracting image info with metadata-extractor: " + e.getMessage());
            // 返回默认值
            return new MediaInfo(null, null, null, "unknown");
        }
    }

    // 静态方法，用于获取视频时长
    public static double getVideoDuration(String filePath) {
        try {
            File file = new File(filePath);
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            Mp4Directory mp4Directory = metadata.getFirstDirectoryOfType(Mp4Directory.class);
            if (mp4Directory != null) {
                Double duration = mp4Directory.getDoubleObject(Mp4Directory.TAG_DURATION_SECONDS);
                if (duration != null) {
                    return duration;
                }
            }
        } catch (ImageProcessingException | IOException e) {
            System.err.println("Error getting video duration with metadata-extractor: " + e.getMessage());
        }
        return 0.0; // 默认返回0
    }

    // 静态方法，用于获取视频尺寸
    public static int[] getVideoDimensions(String filePath) {
        try {
            File file = new File(filePath);
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            Mp4VideoDirectory videoDirectory = metadata.getFirstDirectoryOfType(Mp4VideoDirectory.class);
            if (videoDirectory != null) {
                Integer width = videoDirectory.getInteger(Mp4VideoDirectory.TAG_WIDTH);
                Integer height = videoDirectory.getInteger(Mp4VideoDirectory.TAG_HEIGHT);

                if (width != null && height != null) {
                    return new int[]{width, height};
                }
            }
        } catch (ImageProcessingException | IOException e) {
            System.err.println("Error getting video dimensions with metadata-extractor: " + e.getMessage());
        }
        return null; // 返回null表示获取失败
    }

    // 静态方法，用于获取图片尺寸
    public static int[] getImageDimensions(String filePath) {
        try {
            File file = new File(filePath);
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            // 从不同的目录类型获取图像信息
            ExifSubIFDDirectory exifDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if (exifDirectory != null) {
                Integer width = exifDirectory.getInteger(ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH);
                Integer height = exifDirectory.getInteger(ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT);

                if (width != null && height != null) {
                    return new int[]{width, height};
                }
            }

            // 如果EXIF中没有找到，尝试其他图像目录
            JpegDirectory jpegDirectory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
            if (jpegDirectory != null) {
                Integer width = jpegDirectory.getInteger(JpegDirectory.TAG_IMAGE_WIDTH);
                Integer height = jpegDirectory.getInteger(JpegDirectory.TAG_IMAGE_HEIGHT);

                if (width != null && height != null) {
                    return new int[]{width, height};
                }
            }

            PngDirectory pngDirectory = metadata.getFirstDirectoryOfType(PngDirectory.class);
            if (pngDirectory != null) {
                Integer width = pngDirectory.getInteger(PngDirectory.TAG_IMAGE_WIDTH);
                Integer height = pngDirectory.getInteger(PngDirectory.TAG_IMAGE_HEIGHT);

                if (width != null && height != null) {
                    return new int[]{width, height};
                }
            }
        } catch (ImageProcessingException | IOException e) {
            System.err.println("Error getting image dimensions with metadata-extractor: " + e.getMessage());
        }
        return null; // 返回null表示获取失败
    }

    // 为视频生成缩略图 - 保持原有方法，因为这需要ffmpeg
    public static boolean generateVideoThumbnail(String inputFile, String outputFile) {
        try {
            String[] command = {
                "ffmpeg",
                "-i", inputFile,
                "-ss", "00:00:05",  // 从第5秒截取
                "-vframes", "1",    // 只截取一帧
                "-f", "image2",     // 输出图像格式
                outputFile
            };

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            System.err.println("Error generating video thumbnail: " + e.getMessage());
            return false;
        }
    }

    // 为图片生成缩略图（调整尺寸）- 保持原有方法，因为这需要ffmpeg
    public static boolean generateImageThumbnail(String inputFile, String outputFile) {
        try {
            String[] command = {
                "ffmpeg",
                "-i", inputFile,
                "-vf", "scale=300:200",  // 调整图片大小
                "-vframes", "1",    // 只输出一帧
                outputFile
            };

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            System.err.println("Error generating image thumbnail: " + e.getMessage());
            return false;
        }
    }

    public boolean generateThumbnail(String inputFile, String outputFile, String timeOffset) {
        try {
            String[] command = {
                "ffmpeg",
                "-i", inputFile,
                "-ss", timeOffset,  // 从第几秒截取
                "-vframes", "1",    // 只截取一帧
                "-f", "image2",     // 输出图像格式
                outputFile
            };

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            System.err.println("Error generating thumbnail: " + e.getMessage());
            return false;
        }
    }
}